package com.yss.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yss.common.core.constant.CacheConstants;
import com.yss.common.core.constant.UserConstants;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.text.Convert;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.redis.service.RedisService;
import com.yss.system.domain.SysConfig;
import com.yss.system.mapper.SysConfigMapper;
import com.yss.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;

/**
 * 参数配置 服务层实现
 */
@Slf4j
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {
    @Autowired
    private RedisService redisService;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        this.loadingConfigCache();
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        if (StringUtils.isEmpty(configKey)) {
            throw new BusinessException("获取参数信息失败，请稍后重试！" );
        }
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>();
        wrapper.like("CONFIG_KEY" , configKey);
        SysConfig retConfig = this.getOne(wrapper);
        if (StringUtils.isNotNull(retConfig)) {
            redisService.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabled() {
        String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled" );
        if (StringUtils.isEmpty(captchaEnabled)) {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(SysConfig config) {
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>();
        if (null == config) {
            return this.list(wrapper);
        }
        if (StringUtils.isNotEmpty(config.getConfigName())) {
            wrapper.like("CONFIG_NAME" , config.getConfigName());
        }
        if (StringUtils.isNotEmpty(config.getConfigType())) {
            wrapper.eq("CONFIG_TYPE" , config.getConfigType());
        }
        if (StringUtils.isNotEmpty(config.getConfigKey())) {
            wrapper.like("CONFIG_KEY" , config.getConfigKey());
        }
        if (StringUtils.isNotEmpty(config.getParams())) {
            if (null != config.getParams().get("beginTime" ) && StringUtils.isNotEmpty(config.getParams().get("beginTime" ).toString())) {
                wrapper.ge("CREATE_TIME" , config.getParams().get("beginTime" ));
            }
            if (null != config.getParams().get("endTime" ) && StringUtils.isNotEmpty(config.getParams().get("endTime" ).toString())) {
                wrapper.le("CREATE_TIME" , config.getParams().get("endTime" ));
            }
        }
        wrapper.orderByDesc("CREATE_TIME" );
        return this.list(wrapper);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean insertConfig(SysConfig config) {
        if (null == config) {
            throw new BusinessException("获取要添加的参数信息失败，请稍后重试！" );
        }
        boolean falg = this.save(config);
        if (falg) {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return falg;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean updateConfig(SysConfig config) {
        SysConfig temp = this.getById(config.getConfigId());
        if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
            redisService.deleteObject(getCacheKey(temp.getConfigKey()));
        }
        boolean falg = this.updateById(config);
        if (falg) {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return falg;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(String[] configIds) {
        for (String configId : configIds) {
            SysConfig config = this.getById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new BusinessException(String.format("内置参数【%1$s】不能删除 " , config.getConfigKey()));
            }
            this.removeById(configId);
            redisService.deleteObject(getCacheKey(config.getConfigKey()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = this.list();
        if (CollectionUtils.isEmpty(configsList)) {
            return;
        }
        for (SysConfig config : configsList) {
            if (null == config || StringUtils.isEmpty(config.getConfigKey())) {
                continue;
            }
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*" );
        redisService.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfig config) {
        if (null == config) {
            throw new BusinessException("获取参数信息失败，请稍后重试！" );
        }
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("CONFIG_KEY" , config.getConfigKey());
        SysConfig info = this.getOne(wrapper);
        // 修改的是否判断是否同一个id
        String configId = StringUtils.isEmpty(config.getConfigId()) ? "-1" : config.getConfigId();
        if (StringUtils.isNotNull(info) && !info.getConfigId().equals(configId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
